//
//  DDCompanyMicroPageViewController.m
//  DingDongZP
//
//  Created by Ray on 16/5/4.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDCompanyMicroPageViewController.h"
#import "DDCompanyMicroHeadView.h"
#import "DDCompanySuperinerCell.h"
#import "CCUICreator.h"
#import "DDDiscoverJobCell.h"
#import "DDCompanyHomeService.h"
#import "DDBossInfoService.h"
#import "DDBossInfo.h"
#import "DDCompanyIntroCell.h"
#import "DDProductIntroCell.h"
#import "DDGaoGuanCell.h"
#import "DDNewCattleViewController.h"

#import "WXApi.h"
#import "DDShareView.h"
#import "DDShareManager.h"
#import <MessageUI/MessageUI.h>
#import <AFNetworking/AFNetworking.h>

@interface DDCompanyMicroPageViewController ()
<UITableViewDataSource,
UITableViewDelegate,
DDShareViewDelegate,
MFMessageComposeViewControllerDelegate>

@property (nonatomic, strong) DDCompanyMicroHeadView *headview;
@property (nonatomic, strong) UITableView *tableView;

@property (strong, nonatomic) DDShareView *shareView;

@property (nonatomic, strong) DDCompanyInfo *companyInfo;
@property (nonatomic, strong) DDBossInfo *bossInfo;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic ,strong) DDGaoGuanCell *cell;
@property (nonatomic ,strong) NSMutableArray *arr;

@end

@implementation DDCompanyMicroPageViewController



    


- (void)hand:(UIButton *)button{
    
    button.selected = !button.selected;
    if (button.selected == NO) {
        _cell.renwu.text = @"";
    }else{
        
        _cell.renwu.text = @"高官厚禄看啊加快了关键时刻立法机关拖拉机低空掠过经历几个路口都放假了肯德基了家";
    }
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self datashuju];
    
    
    
    [self addRightButtonItemWithImage:[UIImage imageNamed:@"common_nav_share"] action:@selector(shareButtonClick)];

    self.title = @"我的微主页";
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    DDCompanyMicroHeadView *headView = [[DDCompanyMicroHeadView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, SCREEN_WIDTH*1.06)];
    self.tableView.tableHeaderView = headView;
    self.headview = headView;
    
    ///	back button
    UIButton *back = [UIButton buttonWithFrame:CGRectMake(10, 20, 44, 44)
                                         image:[UIImage imageNamed:@"back"]
                                hilightedImage:nil
                                        target:self
                                      selector:@selector(doBack)];
    [self.view addSubview:back];
    
    
    /// cells
//    [self.tableView registerNib:[UINib nibWithNibName:@"DDProductIntroCell" bundle:nil] forCellReuseIdentifier:@"productCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DDCompanyIntroCell" bundle:nil] forCellReuseIdentifier:@"companyCell"];
    
    [self loadCompanyInfo];
    [self loadBossInfo];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self scrollViewDidScroll:self.tableView];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.alpha = 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - evnets

- (void)setIsShare:(BOOL)isShare
{
    if (_isShare != isShare) {
        _isShare = isShare;
        
        if (_isShare) {
            [self shareButtonClick];
        }
    }
}

- (void)shareButtonClick
{
    CGRect originalBound = self.shareView.actionView.frame;
    originalBound.origin.y +=210;
    self.shareView.actionView.frame = originalBound;
    
    if (!self.shareView.superview) {
        [UIView animateWithDuration:0.3 animations:^{
            [[UIApplication sharedApplication].keyWindow addSubview:self.shareView];
            
            CGRect newBounds = self.shareView.actionView.frame;
            newBounds.origin.y -= 210;
            self.shareView.actionView.frame = newBounds;
        }];
    }
}

- (void)shareCancelButtonOnClick:(UIButton *)button
{
    [self.shareView hide];
}

- (void)doBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - data
- (void)loadCompanyInfo {
    
    [self showLoading];
    [[DDCompanyHomeService sharedService] queryCompanyInfo:^(id responseObject, NSError *error) {
        
        [self hideLoading];
        if ([responseObject isKindOfClass:[DDCompanyInfo class]]) {
            self.companyInfo = responseObject;
            [self.headview setCompanyInfo:self.companyInfo];
            [self.tableView reloadData];
        }
        else {
            [self showErrorWithText:error.domain];
        }
    }];
}

- (void)loadBossInfo {
    
    [[DDBossInfoService sharedService] queryBossInfoWithSuccessBlock:^(id responseObject) {
        DDBossInfo *model = [DDBossInfo yy_modelWithJSON:responseObject[@"data"]];
        [self.headview setBossInfo:model];
        self.bossInfo = model;
        [self.tableView reloadData];
    } failBlock:^(id responseObject, NSError *error) {
        
    }];
}

#pragma mark - tableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arr.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        return 160;
    }if (indexPath.row == 0) {
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        [cell setNeedsLayout];
        [cell layoutIfNeeded];
        return cell.frame.size.height + 10;

        
    }if (indexPath.row == 1) {
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        [cell setNeedsLayout];
        [cell layoutIfNeeded];
        return cell.frame.size.height + 10;

    }
//    NSDictionary *Celldic = [self.arr objectAtIndex:indexPath.row];
//    NSArray *dareArr = [Celldic objectForKey:@"waypoints"];
//    NSDictionary *dic =  [dareArr firstObject];
//    
//    DDJobsDetail *model = [[DDJobsDetail alloc]init];
//    
//    [DDJobsDetail setValuesForKeysWithDictionary:dic];
//    
//    
//        return [DDGaoGuanCell heightWithText:model.jobdesc]+30;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    [cell setNeedsLayout];
    [cell layoutIfNeeded];
    return cell.frame.size.height + 10;



}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return self.tabBarController.tabBar.frame.size.height;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        DDCompanyIntroCell *cell = [tableView dequeueReusableCellWithIdentifier:@"companyCell"];
        
        /// introduce
        cell.nameLab.text = @"团队介绍";
        cell.infoLab.text = self.bossInfo.teamintro;
        cell.infoLab.textColor = [UIColor colorWithRed:180/255.0 green:180/255.0 blue:180/255.0 alpha:1.f];
        return cell;
    }
    else if (indexPath.row == 1) {
        DDCompanyIntroCell *cell = [tableView dequeueReusableCellWithIdentifier:@"companyCell"];
        
        /// introduce
        cell.nameLab.text = @"产品介绍";
        cell.infoLab.textColor = [UIColor colorWithRed:180/255.0 green:180/255.0 blue:180/255.0 alpha:1.f];

        cell.infoLab.text = self.companyInfo.product_strengths;
        return cell;
    }
    else if (indexPath.row == 2) {
        DDCompanySuperinerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"superCell"];
        if (!cell) {
            cell = [[DDCompanySuperinerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"superCell"];
            /// apple's bug!
            cell.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
        }

        cell.companyInfo = self.companyInfo;
        return cell;
    }
    else {
         DDGaoGuanCell*cell = [tableView dequeueReusableCellWithIdentifier:@"DDGaoGuanCell"];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DDGaoGuanCell" owner:self options:nil] lastObject];
        }
            [cell updateViewWithData:(DDJobsDetail *)self.dataSource[indexPath.row]];
        [[LDBossInfoNet sharedInstance] viewMyselfAllJobsKinds:^(NSArray<NSDictionary *> * _Nonnull dictArr) {
            
            NSLog(@"^^^^^%@",dictArr);
        } failure:^(id  _Nonnull error) {
            
        }];
        cell.zhiWei.text = [NSString stringWithFormat:@"%@",[[_arr objectAtIndex:indexPath.row]objectForKey:@"jobtitle"] ];
        cell.add.text = [NSString stringWithFormat:@"%@",[[_arr objectAtIndex:indexPath.row]objectForKey:@"city"] ];
        cell.price.text =[NSString stringWithFormat:@"%@",[[_arr objectAtIndex:indexPath.row]objectForKey:@"salary"] ];
        cell.xueli.text =[NSString stringWithFormat:@"%@",[[_arr objectAtIndex:indexPath.row]objectForKey:@"edu"] ];
        cell.year.text =[NSString stringWithFormat:@"%@",[[_arr objectAtIndex:indexPath.row]objectForKey:@"experience"] ];
        cell.miaoshu.text =[NSString stringWithFormat:@"%@",[[_arr objectAtIndex:indexPath.row]objectForKey:@"jobdesc"] ];
        
        
        return cell;
    }
    return [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"haha"];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSLog(@"%ld",(long)indexPath.section);
    NSLog(@"%ld",indexPath.row);
    
}

- (void)datashuju{
    
    _arr = [NSMutableArray array];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:[DDLoginUserManager token] forKey:@"hashedpassword"];
    [dict setValue:[DDLoginUserManager account] forKey:@"mobile"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/json",@"text/plain",@"text/html", nil];
    NSString *url = [NSString stringWithFormat:@"http://114.55.59.142/appws/employer_query_companyinfo.php"];
    
    [manager POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    }  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        _arr = [[responseObject objectForKey:@"data"]objectForKey:@"jobs"];
        
        [_tableView reloadData];
        
    }
     
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          }];

}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return _dataSource;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.navigationController.navigationBar.alpha = scrollView.contentOffset.y / 200.0;
}

#pragma mark
#pragma mark - Getters and Setters

- (DDShareView *)shareView
{
    if (!_shareView) {
        _shareView = (DDShareView *)[[NSBundle mainBundle] loadNibNamed:@"DDShareView" owner:self options:nil].firstObject;
        
        [_shareView.cancelButton addTarget:self action:@selector(shareCancelButtonOnClick:) forControlEvents:UIControlEventTouchUpInside];
        _shareView.delegate = self;
        
        WEAKSELF
        [_shareView bk_whenTapped:^{
            [weakSelf.shareView hide];
        }];
    }
    
    return _shareView;
}

#pragma mark
#pragma mark - DDShareViewDelegate

- (void)shareViewButtonClick:(DDShareType)sharetype
{
    switch (sharetype) {
        case DDShareTypeWXTimeLine: {
            [self shareToWeiXinWithType:DDShareTypeWXTimeLine];
        }
            break;
            
        case DDShareTypeWeiXinSession: {
            [self shareToWeiXinWithType:DDShareTypeWeiXinSession];
        }
            break;
            
        case DDShareTypeWeiBo: {
            [self shareToWeibo];
        }
            break;
            
        case DDShareTypeSMS: {
            [self shareToSMS];
        }
            break;
            
        default:
            break;
    }
}

- (void)shareToWeiXinWithType:(DDShareType)shareType
{
    int scene = 0;
    if (shareType == DDShareTypeWeiXinSession) {
        scene = WXSceneSession;
    } else {
        scene = WXSceneTimeline;
    }
    NSString *shareURL = [DDAPIGenerate h5URLWithPath:self.companyInfo.shareh5];
    UIImage *shareImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[DDAPIGenerate imageURLWithPath:self.companyInfo.sharelogo]]]];
    
    [[DDShareManager shareInstance] shareToWeiXinWithScene:scene title:self.companyInfo.sharetitle description:self.companyInfo.sharedesc webpageUrl:shareURL image:shareImage isVideo:NO];
}

- (void)shareToWeibo
{
    UIImage *shareImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[DDAPIGenerate imageURLWithPath:self.companyInfo.sharelogo]]]];
    
    [[DDShareManager shareInstance] shareToWeibo:nil title:self.companyInfo.sharetitle description:self.companyInfo.sharedesc webpageUrl:[DDAPIGenerate h5URLWithPath:self.companyInfo.shareh5] image:shareImage VC:self isVideo:NO];
}

- (void)shareToSMS
{
    if( [MFMessageComposeViewController canSendText] ){
        
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        controller.body = [NSString stringWithFormat:@"%@ %@",self.companyInfo.sharedesc,[DDAPIGenerate h5URLWithPath:self.companyInfo.shareh5]];
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES
                         completion:^{
                         }];
        [[[[controller viewControllers] lastObject] navigationItem] setTitle:@"Invite"];//修改短信界面标题
    }else{
        
        [UIAlertView bk_alertViewWithTitle:@"提醒" message:@"设备不支持短信功能"];
    }
}


#pragma mark
#pragma mark - MFMessageComposeViewControllerDelegate
/**
 *  发送完短信的回调
 *
 *  @param controller
 *  @param result
 */
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    
    [controller dismissViewControllerAnimated:NO completion:^{
        
    }];//关键的一句   不能为YES
    
    switch (result) {
            
        case MessageComposeResultCancelled:
            
            [self showToastOnCenter:@"取消发送"];
            break;
        case MessageComposeResultFailed:// send failed
            
            [self showToastOnCenter:@"发送失败"];
            break;
        case MessageComposeResultSent:
            
            [self showToastOnCenter:@"发送成功"];
            break;
        default:
            break;
    }
}


@end
